﻿using Microsoft.EntityFrameworkCore;
using PaymentServiceFactory.Data;
using PaymentServiceFactory.Services.Interfaces;

namespace PaymentServiceFactory.Services.Repositories
{
    public class OrderDetrInfoRepository : IOrderDetrInfoRepository
    {
        private readonly AppDbContext _context;

        public OrderDetrInfoRepository(AppDbContext context)
        {
            _context = context;
        }

        public async Task<OrderDetail> GetOrderDetailAsync(string orderId)
        {
            //return await _context.OrderDetails
            //    .FirstOrDefaultAsync(o => o.OrderId == orderId)
            //    ?? throw new KeyNotFoundException($"订单 {orderId} 未找到");
            return await _context.OrderDetails
        .AsNoTracking()  // 不需要更改跟踪时使用
        .FirstOrDefaultAsync(o => o.OrderId == orderId)
        ?? throw new KeyNotFoundException($"订单 {orderId} 未找到");
        }

        public async Task UpdateOrderStatusAsync(string orderId, string status)
        {
            var order = await GetOrderDetailAsync(orderId);
            order.PaymentStatus = status;
            _context.Update(order);
            await _context.SaveChangesAsync();
        }
        //public async Task UpdateOrderStatusAsync(string orderId, string status)
        //{
        //    // 使用单次查询更新（减少上下文跟踪开销）
        //    var result = await _context.OrderDetails
        //        .Where(o => o.OrderId == orderId)
        //        .ExecuteUpdateAsync(setters =>
        //            setters.SetProperty(o => o.PaymentStatus, status));

        //    if (result == 0)
        //        throw new KeyNotFoundException($"订单 {orderId} 未找到");
        //    result.PaymentStatus = status;
        //    _context.Update(order);
        //    await _context.SaveChangesAsync();
        //}
    }
}
